const app = getApp()

var Charts = require('../../utils/wxcharts.js');
var chart = []
const W = wx.getSystemInfoSync().windowWidth;
const rate = 750.0 / W;
const code_w = 580 / rate;
const code_h = 300 / rate;

Page({
  data: {
    questionnaireList: [],
    questionnaireStat: [{},
      {},
    ],
    questions: [],
    create_time: "",
    selectedQsid: '',
    selectedTitle: '',
    maxOptions: ["A", "B", "C", "D", "E", "F", "G", "H"],
    idCollections: [],
    nullData: false,
    windowHeight: 0,
    windowWidth: 0,
    codeSrc: '',
    haveGetCodeSrc: false,
    modalHidden:true
  },

  onLoad(options) {
    console.log(options)
    this.setData({
      selectedQsid: options.selectedQsid,
      selectedTitle: options.selectedTitle,
      questionnaireStat: [],
      questions: []
    })
    console.log("当前问卷标题：" + this.data.selectedTitle)
    console.log("已进入问卷id：" + this.data.selectedQsid + " 的数据分析界面")
    const db = wx.cloud.database({});
    db.collection('answers').where({
      q_id: this.data.selectedQsid
    }).get({
      success: (res) => {
        if (res.data.length == 0) {
          console.log('无数据')
          this.setData({
            nullData: true
          })
        } else {
          this.setData({
            questionnaireList: res.data
          })
          console.log("查询之后已得到的答案集合：")
          console.log(this.data.questionnaireList)
          db.collection('questions').where({
            q_id: this.data.selectedQsid
          }).get({
            success: (res) => {
              this.setData({
                questions: res.data[0].questions
              })
              console.log("目前获得的问题列表：")
              console.log(this.data.questions)
              var i, j, l
              var questionnaireStat = []
              var idCol = []
              for (i = 0; i < this.data.questions.length; i++) {
                var tempStat = []
                if (this.data.questions[i].type == "input") {
                  for (j = 0; j < this.data.questionnaireList.length; j++) {
                    if(this.data.questionnaireList[j].ans[i].hasOwnProperty("text")){
                      console.log("一条填空题记录答案：  " + this.data.questionnaireList[j].ans[i].text)
                      tempStat.push(this.data.questionnaireList[j].ans[i].text)
                    }
                   
                  }
                  questionnaireStat.push(tempStat)
                } else if (this.data.questions[i].type == "radio") {
                  var k
                  var num = 0
                  for (j = 0; j < this.data.questions[i].options.length; j++) {
                    console.log("此时统计的选项为" + this.data.maxOptions[j])
                    for (k = 0; k < this.data.questionnaireList.length; k++) {
                      if(this.data.questionnaireList[k].ans[i].hasOwnProperty("options")){
                        console.log(this.data.questionnaireList[k].ans[i].hasOwnProperty("options"))
                        console.log("此人的选择为" + this.data.questionnaireList[k].ans[i].options[0].option_id)
                      if (this.data.questionnaireList[k].ans[i].options[0].option_id == this.data.maxOptions[j]) {
                        num = num + 1
                      }
                      }
                    }
                    console.log("选择" + this.data.questions[i].options[j].option_id + "选项的人数为:")
                    console.log(num)
                    tempStat.push(num)
                    num = 0
                  }
                  questionnaireStat.push(tempStat);

                } else if (this.data.questions[i].type == "checkbox") {
                  var k, t
                  var num = 0
                  for (j = 0; j < this.data.questions[i].options.length; j++) {
                    console.log("此时统计的选项为" + this.data.maxOptions[j])
                    for (k = 0; k < this.data.questionnaireList.length; k++) {
                      if(this.data.questionnaireList[k].ans[i].hasOwnProperty("options")){
                      for (t = 0; t < this.data.questionnaireList[k].ans[i].options.length; t++) {
                        console.log(this.data.questionnaireList[k].ans[i].hasOwnProperty("options"))
                          if (this.data.questionnaireList[k].ans[i].options[t].option_id == this.data.maxOptions[j]) {
                            num = num + 1
                            console.log(this.data.questionnaireList[k].ans[i].options[t].option_id)
                            console.log("选择此选项的人数+1")
                          }
                      }
                    }
                    }
                    console.log("选择" + this.data.questions[i].options[j].option_id + "选项的人数为:")
                    console.log(num)
                    tempStat.push(num)
                    num = 0
                  }
                  questionnaireStat.push(tempStat);
                }
              }
              console.log("答案数据统计集合：")
              console.log(questionnaireStat)
              this.setData({
                questionnaireStat: questionnaireStat
              })
              for (l = 0; l < this.data.questionnaireStat.length; l++) {
                var id = 'columnCanvas' + l.toString()
                idCol.push(id)
                this.setData({
                  idCollections: idCol
                })
                if (this.data.questions[l].type == 'radio' || this.data.questions[l].type == 'checkbox') {
                  this.chartsMake(this.data.questionnaireStat[l], l)
                }
              }
            }

          })
        }
      }
    })
  },
  chartsMake: function (stat, l) {
    var options = []
    var j
    for (j = 0; j < this.data.questions[l].options.length; j++) {
      options.push(this.data.maxOptions[j])
    }
    console.log("绘制一幅图表")
    console.log(stat)
    let _this = this
    chart[l] = new Charts({
      canvasId: 'columnCanvas' + l.toString(),
      dataPointShape: false,
      type: 'column',
      categories: options,
      series: [{
        name: '选择人数',
        data: this.data.questionnaireStat[l]
      }],
      title: {
        name: this.data.questions[l].title,
        color: '#333333',
        fontSize: 14
      },
      yAxis: {
        disableGrid: true,
        type: 'calibration',
        min: 0,
        interval: 1,
        disabled: true,
        format: function (val) {
          return val + '人';
        },
        fontColor: "#1b6368"
      },
      width: code_w,
      height: code_h,
      dataLabel: true,
    });
  },
  getCodeSrc() {
    wx.showLoading({
      title: '',
    });
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: this.data.envId
      },
      data: {
        type: 'getMiniProgramCode',
        code: this.data.selectedQsid,
      }
    }).then((resp) => {
      console.log(this.data.codeSrc);
      this.setData({
        haveGetCodeSrc: true,
        codeSrc: resp.result
      });
      wx.hideLoading();
    }).catch((e) => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  },
  showQRcode: function () {
    this.getCodeSrc();
    console.log(this.data.codeSrc);
    wx.downloadFile({
      url: this.data.codeSrc,
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success:function(dres){
            console.log(dres);
            console.log("saved!!")
          },
          fail(e)
          {
            console.log(e);
          }
        })
      },
      fail(e)
          {
            console.log(e);
          }
    })
    this.setData({
      modalHidden: false,
    })
    console.log(this.data.modalHidden);
  },
  modalCandel: function () {
    // do something
    this.setData({
      modalHidden: true,
    })
  },

  modalConfirm: function () {
    // do somethings
    this.setData({
      modalHidden: true,
    })
  },
  copyCode: function() {
    wx.setClipboardData({
      data:this.data.selectedQsid,
      success: function () {
        wx.showToast({
          title: '复制成功',
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  canvasIdErrorCallback: function (e) {
    console.error(e.detail.errMsg)
  },

  onReady: function () {
    wx.getSystemInfo({
      success: res => {
        this.setData({
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        })
      }
    })
  },

})